package com.eascs.finance.admin.common.interceptor;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台白名单过滤
 */
public class ManagerInterceptor extends HandlerInterceptorAdapter {
	Logger logger = LoggerFactory.getLogger(ManagerInterceptor.class);

	private static Map<String, String> managers = new HashMap<>();

	{
		PermissionConfig config  = PermissionConfig.get();
		String           manager = config.getWhiteList();
		if (StringUtil.isNotBlank(manager)) {
			for(String user : manager.split(",")) {
				managers.put(user, user);
			}
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 记录访问日志
		try {
			String requestUri = request.getRequestURI();
			//过滤监控和首页记录
			if (!"/".equals(requestUri) && !"/system-admin/monitor/status".equals(requestUri)
					&& !"/user/noauth".equals(requestUri)) {
				logger.debug("access log,url:{},ip:{}", request.getRequestURI(), request.getRemoteAddr());
				User user = UserHolder.getUser();
				if (null == managers.get(user.getAccount())) {
					response.sendRedirect("/user/noauth");
					user.setCloseAuth(false);
					return false;
				}else {
					user.setCloseAuth(true);
				}
			}
		} catch (Exception e) {
			logger.error("记录用户访问日志失败,errMsg:{}", e);
			e.printStackTrace();
		}

		return super.preHandle(request, response, handler);
	}

}
